package com.chaowei.lims.utils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.Marshal;
import org.ksoap2.serialization.MarshalFloat;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import com.chaowei.lims.entity.WcfWrapper;

import android.app.Activity;
import android.os.AsyncTask;
import android.util.Log;
import android.view.Gravity;
import android.widget.PopupWindow;

public class SoapRequest extends AsyncTask<Object, WcfWrapper, SoapObject> {
	AsyncOptUIListener postExecuteListner;

	public SoapRequest(AsyncOptUIListener listener) {
		postExecuteListner = listener;
	}

	@Override
	protected SoapObject doInBackground(Object... params) {
		SoapObject response = null;
		try {
			WcfWrapper wrap = (WcfWrapper) params[0];
			SoapObject req = new SoapObject(wrap.Namespace, wrap.MethodName);
			for (Map.Entry<String, Object> entry : wrap.MethodParameter
					.entrySet()) {
				req.addProperty(entry.getKey(), entry.getValue());
			}

			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
					SoapEnvelope.VER11);
			envelope.dotNet = true;
			envelope.implicitTypes = true;
			envelope.setOutputSoapObject(req);

			HttpTransportSE transport = new HttpTransportSE(wrap.Url);
			transport.debug = true;
			try {
				transport.call(wrap.SoapAction, envelope);
			} catch (IOException e) {
				e.printStackTrace();
			} catch (XmlPullParserException e) {
				e.printStackTrace();
			}
			if (envelope.bodyIn instanceof SoapObject) {
				response = (SoapObject) envelope.bodyIn;

			} else if (envelope.bodyIn instanceof SoapFault) {
				SoapFault soapFault = (SoapFault) envelope.bodyIn;
				throw new Exception(soapFault.getMessage());
			}

		} catch (Exception e) {
			Log.i(e.getMessage(), e.getMessage());
			return null;
		}
		return response;

	}

	@Override
	protected void onPostExecute(SoapObject result) {
		postExecuteListner.AsyncOpt(result);
	}

}
